<script>
  import affiche from '../children/affiche'
  import trendChart from '../children/trendChart'
  import Constant from 'common/constant'
  import TeamHeader from '../TeamHeader'
  import RemoteDAO from 'common/remoteDAO'

  export default {
    data () {
      return {
        gameId: this.$route.query.gameId || '',
        attendedTeamId: ['-1'],
        teamChartList: [],
        chartData: [],
        chartDateArr: [],
        rank: 1,
        // 比赛详情
        gameDetail: {},
        // 比赛头
        gameTitle: this.$route.query.gameName
      }
    },

    components: {
      affiche,
      trendChart,
      TeamHeader
    },

    created () {
      this.getAnnouncement()
    },

    mounted () {
      TDAPP.onEvent('13032', "", { gameid: this.gameId,
        usercode: localStorage.getItem('userCode') })
      TDAPP.send()
      this.getGameDetail()
      this.getGameTeams()
      this.getAttendedTeam()
    },

    filters: {
      profitFilter (val) {
        const symbol = parseFloat(val) > 0 || Math.abs(parseFloat(val)).toFixed(2) === '0.00'
          ? '+' : '-'
        return val !== undefined ? symbol + Math.abs(parseFloat(val)).toFixed(2) + '%' : '-'
      }
    },

    computed: {
      timeZone () {
        return this.filterTime(this.gameDetail.BEGIN_DATE, 'MM月DD日')
          + '-' + this.filterTime(this.gameDetail.END_DATE, 'MM月DD日')
      },

      teamList () {
        return this.$store.state.team.teamList
      },

      createrHead () {
        if (this.gameDetail.GAME_KIND === Constant.game.kind.OFFICIAL
          || !this.gameDetail.CREATER_HEAD) {
          return  Constant.url.OFFICIAL_LOGO
        } else {
          return this.gameDetail.CREATER_HEAD
        }
      },

      announcementList () {
        return this.$store.state.team.announcementList
      },

      afficheText () {
        let result = []
        result.push(this.$store.state.team.announcementList[0])
        return result
      },
      
      gameStatus () {
        const gameStepMap = {
          '0': '未开始报名',
          '1': '报名中',
          '2': '报名结束',
          '3': '比赛中',
          '4': '比赛结束',
          '5': '比赛关闭'
        }
        
        return gameStepMap[this.gameDetail.GAME_STEP] || ''
      }
    },

    methods: {
      goRoute () {
        this.$router.push({name: 'Announcement'})
      },

      trophyClass (rank) {
        return rank < 4 ? 'icon-trophy-' + rank : 'icon-trophy-u'
      },

      resultClass(bool) {
        return bool ? 'icon-v' : 'icon-loss'
      },

      profitColor (profit = '0.00') {
        return {
          color: parseFloat(profit).toFixed(2) >= 0 ? '#FF3333' : '#89CD4C'
        }
      },

      /**日期格式转换 
      * @param {String} date 输入日期，格式YYYYMMDD
      * @param {String} format 默认：'MM月DD日'，可选 'MM月DD日'、'YYYY.MM.DD'
      */
      filterTime (date, format) {
        let result = ''
        if (date) {
          let year = ''
          let month = ''
          let day = ''
          switch(format) {
            case 'MM月DD日':
              month = date.slice(4, 6)
              day = date.slice(6, 8)
              result = `${month}月${day}日`
              break
            case 'YYYY.MM.DD':
              year = date.slice(0, 4)
              month = date.slice(4, 6)
              day = date.slice(6, 8)
              result = `${year}.${month}.${day}`
              break
            default:
              month = date.slice(4, 6)
              day = date.slice(6, 8)
              result = `${month}月${day}日`
              break
          }
        }
        return result
      },

      toTeamDetail (item) {
        this.$router.push({ path: 'team-detail', query: {
          gameId: item.GAME_ID,
          gameTitle: this.gameTitle,
          hasAttended: this.attendedTeamId.length > 0
        }})
      },

      // 获取比赛详情
      getGameDetail () {
        RemoteDAO.callUC12008302({
          gameId: this.gameId,
          pageNum: '1',
          pageSize: '50'
        }, res => {
          this.gameDetail = res.data.body[0]
          console.info('game detail', this.gameDetail)
        })
      },

      // 获取比赛团队列表
      getGameTeams () {
        RemoteDAO.callUC12008302({
          gameId: '',
          gameType: 'TDS',
          gameStatus: '',
          pageSize: '50',
          pageNum: '1',
          upGameId: this.gameId
        }, res => {
          this.$store.dispatch('setTeamList', res.data.body)
          console.info('teamList', res.data.body)
          this.getChartData()
          .catch(
            (reason) => {
              console.warn(reason)
            }
          )
        })
      },

      // 获取参加的子团队信息
      getAttendedTeam () {
        RemoteDAO.callUC12008303({
          userCode: localStorage.getItem('userCode'),
          actionFlag: 3,
          pageSize: 1,
          pageNo: 1,
          gameID: this.gameId
        }, resp => {
          // 是否参加了比赛
          if (resp.error !== '1') {
            this.attendedTeamId = resp.data.body.map(t => t.GAME_ID)
          } else {
            this.attendedTeamId = []
          }
        })
      },

      // 获取公告
      getAnnouncement () {
        this.$store.dispatch('setAnnouncementList', [{NOTICE_TEXT: ''}])
        RemoteDAO.callUC12000054({
          relationId: this.gameId
        }, resp => {
          console.info('Announcement List',  resp.data.body)
          if(resp.data.body.length > 0) {
            let list = resp.data.body.map(e => {
              e.SUBMIT_DATE = this.filterTime(e.SUBMIT_DATE, 'YYYY.MM.DD')
              return e
            })
            this.$store.dispatch('setAnnouncementList', list)
          }
        })
        // let list = this.afficheData.map(e => {
        //   e.SUBMIT_DATE = this.filterTime(e.SUBMIT_DATE, 'YYYY.MM.DD')
        //   e.SUBMIT_TIME = new Date(parseInt(e.SUBMIT_TIME)).toLocaleTimeString()
        //   return e
        // })
        // this.$store.dispatch('setAnnouncementList', list)
      },

      updateChart (chartInstance, chartDateArr, chartData) {
        chartInstance.updateOpt(chartDateArr, chartData)
      },

      // 获取折线图数据以及收益率数据
      getChartData () {
        return new Promise((resolve, reject) => {
          RemoteDAO.getSubteamList({
            upGameId: this.gameId
            // upGameId: '201705210050005222'
          }, resp => {
            const { teamList = [] } = resp.data
            if(teamList.length > 0) {
              const teamChartList = teamList.map(e => {
                return JSON.parse(e)
              })
              //chart数据，输出格式[name: Sring, data: Array]
              const chartData = teamChartList.map(e => {
                return {
                  name: e.gameName,
                  data: JSON.parse(e.avgProfitTrend).map(item => { 
                    return Number(item).toFixed(2) })
                }
              })
              console.info('teamChartList', teamList)
              console.info('chart data', chartData)
              this.teamChartList = teamChartList
              this.chartData = chartData
              //chart日期数组
              const chartDateArr = JSON.parse(teamChartList[0].avgProfitDays)
                .map(e => {
                  return this.filterTime(e, 'YYYY.MM.DD')
                })
              this.chartDateArr = chartDateArr

              if (teamChartList.length > 0 
                && teamChartList.length === this.teamList.length) {
                this.updateTeamListWithChartData(teamChartList)
              }

              resolve({ chartDateArr, chartData })
            } else {
              reject('teamList is empty')
            }
          })
				})
      },

      // 同步子团队的收益信息
      updateTeamListWithChartData (teamChartList) {
        const { teamList = [] } = this.$store.state.team
        const teamListWithChartData = teamChartList.map(t => {
          return Object.assign({}, t, teamList.find(item => item.GAME_ID === t.gameId))
        })
        this.$store.dispatch('setTeamList', teamListWithChartData)
      },

      // 分享
      onShare () {
        const usercode = localStorage.getItem('userCode') || ''
        const pagename = 'teamgame.gamedetail'
        const shareContent = {
          gameDetail: this.gameDetail,
          chartData: this.chartData,
          chartDateArr: this.chartDateArr
        }
        const url = 'https://dl.app.gtja.com/yyz/data/api/niurenshare/share'

        const icon = "https://dl.app.gtja.com/nrng/shareimages/niuniu.jpg"
        const title = '牛人牛股团队赛开始啦'
        const frt = this.teamChartList.find(t => t.avgProfitRank === '1') || {}
        const content = `本王正在参加这场${this.gameDetail.GAME_NAME}, 目前${frt.gameName || this.teamList[0].GAME_NAME}团队收益最高，你也快来加入吧！`

        $.ajax({
          url: url,
          type: 'POST',
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify({ 
            usercode, 
            type: pagename, 
            content: JSON.stringify(shareContent) 
          }),
          success: function (resp) {
            console.info('share-resp', resp)
            const shareUrl = 'https://dl.app.gtja.com/nrng/newShares/team-game-home.html' + 
              '?userCode=' + usercode + 
              '&url=' + resp.url +
              '&title=' + title +
              '&content=' + content
            RemoteDAO.share(title, content, shareUrl, 'title', icon)
          },
          error: function (e) {
            alert('error:'+JSON.stringify(e));
          }
        })

      },

      // 股林分享
      onShareSpecial () {
        const usercode = localStorage.getItem('userCode') || ''
        const pagename = 'teamgame.glgamedetail'
        const url = 'https://dl.app.gtja.com/yyz/data/api/niurenshare/share'

        const frt = this.teamChartList.find(t => t.avgProfitRank === '1') || {}
        const icon = "https://dl.app.gtja.com/web/gulindahui/share/gulinshare.jpg"
        const title = !!frt.avgProfitRank
          ? `${frt.gameName  || '少林派'}收益率百分之${parseFloat(frt.avgProfit).toFixed(2)},目前股林第一门派`
          : `股林大会比赛开始啦`
        const content = '快和我一起参加股林大会，问鼎最强门派吧！'
        
        $.ajax({
          url: url,
          type: 'POST',
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify({
            usercode,
            type: pagename
          }),
          success: function (resp) {
            const shareUrl = 'https://dl.app.gtja.com/nrng/newShares/gldh-game-martial.html' + 
              '?usercode=' + usercode +
              '&source=teamGameDetail' + 
              '&title=' + title +
              '&content=' + content
            RemoteDAO.share(title, content, shareUrl, 'title', icon)
          }
        })
      },

      backToSquare () {
        $.ajax({
          url: 'https://dl.app.gtja.com/nrng/gldh/gldh.json',
          type: 'GET',
          dataType: 'jsonp',
          jsonp: 'callback',
          jsonpCallback: 'square',
          success: resp => {
            window.location.href = resp.path
          }
        })
      },

      onShowRule () {
        this.$router.push({ path: '/game/rules3' })
      }
    }
  }
</script>